import 'package:flutter/material.dart';
import 'package:xindong/widgets/container/xindong_empty_container.dart';
import 'package:xindong/widgets/gift/view/xindong_songli_grid_view.dart';
import 'package:xindong/widgets/xindong_common_yemian_indicator.dart';

class XinDongSongLiYeMianView extends StatefulWidget {
  final List dataList;

  const XinDongSongLiYeMianView({Key? key, required this.dataList}) : super(key: key);

  @override
  State<XinDongSongLiYeMianView> createState() => _XinDongSongLiYeMianViewState();
}

class _XinDongSongLiYeMianViewState extends State<XinDongSongLiYeMianView>
    with AutomaticKeepAliveClientMixin, SingleTickerProviderStateMixin {
  late final TabController tabController;

  // 一页8个
  final int yemianSize = 8;

  // 分组数据
  List<List> groupList = [];

  // 当前分组下标
  int currentGroupIndex = 0;

  // 总共分组数
  int totalGroupCount = 0;

  // 分组数据
  void generateData() {
    totalGroupCount = ((widget.dataList.length / yemianSize) + (widget.dataList.length % yemianSize == 0 ? 0 : 1)).toInt();
    // 分组数据
    groupList.clear();
    var residueArray = List.from(widget.dataList); // 要深copy
    for (int i = 0; i < totalGroupCount; i++) {
      if (residueArray.length <= yemianSize) {
        groupList.add(residueArray);
      } else {
        groupList.add(residueArray.sublist(0, yemianSize));
        // 移除已使用的
        residueArray.removeRange(0, yemianSize);
      }
    }
  }

  // 避免状态重置
  @override
  bool get wantKeepAlive {
    generateData();
    return true;
  }

  @override
  void initState() {
    super.initState();
    generateData();
    tabController = TabController(length: totalGroupCount, vsync: this);
    tabController.addListener(() {
      currentGroupIndex = tabController.index;
      setState(() {});
    });
  }

  @override
  void dispose() {
    tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return XinDongEmptyContainer(
      dataList: groupList,
      emptyTips: "",
      child: Stack(
        alignment: Alignment.center,
        fit: StackFit.expand,
        clipBehavior: Clip.none,
        children: [
          // 分页
          TabBarView(
            controller: tabController,
            children: groupList.map((e) => XinDongSongLiGridView(dataList: e)).toList(),
          ),

          // 指示器
          Positioned(
            bottom: 0,
            child: XinDongCommonYeMianIndicator(
              currentIndex: currentGroupIndex,
              totalCount: totalGroupCount,
            ),
          ),
        ],
      ),
    );
  }
}
